//
//  PhotoBrowserCell.swift
//  TYHWeibo
//
//  Created by IOS on 15/8/18.
//  Copyright © 2015年 IOS. All rights reserved.
//

import UIKit
import SDWebImage

class PhotoBrowserCell: UICollectionViewCell {
    
    var url: NSURL? {
        didSet {
            //显示菊花
            indicator.startAnimating()
            
            //重置scrollView 
            resetScrollView()
            
            imageView.image = nil
            //模拟延时
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                self.imageView.sd_setImageWithURL(self.url) { (image, error, _, _) -> Void in
                    
                    self.indicator.stopAnimating()
                    if image == nil {
                        print("图片获取失败")
                        return
                    }
                    self.setupImagePosition()
                }
            })
            
        
        }
    }
    //重置scrollView 的偏移属性
    private func resetScrollView() {
        scrollView.contentInset = UIEdgeInsetsZero
        scrollView.contentSize = CGSizeZero
        scrollView.contentOffset = CGPointZero
    }
    private func setupImagePosition() {
        let s = self.displaySize(imageView.image!)
        
        if s.height < scrollView.bounds.height {
            let y = (scrollView.bounds.height - s.height) * 0.5
            imageView.frame = CGRect(origin: CGPointZero, size: s)
            scrollView.contentInset = UIEdgeInsets(top: y, left: 0, bottom: y, right: 0)
        } else{
            imageView.frame = CGRect(origin: CGPointZero, size: s)
            scrollView.contentSize = s
        }
        
        
        
    }
    
    
    private func displaySize(image: UIImage) -> CGSize{
        //图像高宽比
        let scale = image.size.height / image.size.width
        let h = scrollView.bounds.width * scale
        return CGSize(width: scrollView.bounds.width, height: h)
    }
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(scrollView)
        scrollView.addSubview(imageView)
        contentView.addSubview(indicator)
//        scrollView.backgroundColor = UIColor.redColor()
        
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[sv]-20-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["sv": scrollView]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[sv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["sv": scrollView]))
        
        indicator.translatesAutoresizingMaskIntoConstraints = false
        contentView.addConstraint(NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
        contentView.addConstraint(NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0))
        
        prepareScrollView()
        
    }
    
    private func prepareScrollView() {
        scrollView.delegate = self
        
        scrollView.minimumZoomScale = 0.3
        scrollView.maximumZoomScale = 2.0
    }
    
    //懒加载
    private lazy var scrollView = UIScrollView()
    lazy var imageView = UIImageView()
    
    //菊花
    private lazy var indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
    
}

extension PhotoBrowserCell: UIScrollViewDelegate {
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imageView
    }
    
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        var offsetX = (scrollView.bounds.width - view!.frame.width) * 0.5
        offsetX = offsetX < 0 ? 0 : offsetX
        var offsetY = (scrollView.bounds.height - view!.frame.height) * 0.5
        offsetY = offsetY < 0 ? 0 : offsetY
        scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: 0, right: 0)
    }
    
    
}




